package com.jml.netty.手写dubbo.server.register;

import org.I0Itec.zkclient.ZkClient;


public class ZkServiceRegistration {

    /**
     * zk连接地址
     */
    private final String zkServers = "127.0.0.1";
    /**
     * 会话时间
     */
    private final int connectionTimeout = 5000;
    /***
     * zkClient
     */
    private ZkClient zkClient;

    private String rootNamePath = "/jmlrpc";

    public ZkServiceRegistration() {
        // 1.创建zk连接
        zkClient = new ZkClient(zkServers, connectionTimeout);
    }
    //服务注册  (参数：服务名称:com.jml.netty.手写dubbo.api.MemberService  ， 地址:jmlrpc://127.0.0.1:9001)
    public void registr(String serviceName, String addres) {
        // 路径：/jmlrpc是否存在，不存在就创建，使用持久节点，接口路径都是用临时节点
        if (!zkClient.exists(rootNamePath)) {
            zkClient.createPersistent(rootNamePath);
        }
        //  /jmlrpc/com.jml.netty.手写dubbo.api.MemberService
        String serviceNode = rootNamePath + "/" + serviceName;
        if (!zkClient.exists(serviceNode)) {
            zkClient.createPersistent(serviceNode);
        }
        //  /jmlrpc/com.jml.netty.手写dubbo.api.MemberService/providers
        String providers = serviceNode + "/providers";
        if (!zkClient.exists(providers)) {
            zkClient.createPersistent(providers);
        }
        // jmlrpc/com.jml.netty.手写dubbo.api.MemberService/providers/jmlrpc://127.0.0.1:9001
        String servicePathAddres = providers + "/" + addres;
        if (zkClient.exists(servicePathAddres)) {
            zkClient.delete(servicePathAddres);
        }
        // 临时节点缓存地址
        zkClient.createEphemeral(servicePathAddres);
        System.out.println("rootNamePath:"+rootNamePath);
        System.out.println("serviceNode:"+serviceNode);
        System.out.println("providers:"+providers);
        System.out.println("servicePathAddres:"+servicePathAddres);
    }
//rootNamePath:     /jmlrpc
//serviceNode:      /jmlrpc/com.jml.netty.手写dubbo.api.MemberService
//providers:        /jmlrpc/com.jml.netty.手写dubbo.api.MemberService/providers
//servicePathAddres:/jmlrpc/com.jml.netty.手写dubbo.api.MemberService/providers/jmlrpc%3A%2F%2F127.0.0.1%3A8093
}
